package com.talking.tool;

import com.talking.pojo.ChatMsg;
import com.talking.pojo.Group;
import com.talking.pojo.SystemVariable;
import com.talking.pojo.User;

import java.io.*;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MsgFileOutput {
    private ChatMsg chatMsg;
    private int id;
    private String content;
    private String time;
    private File files;
    private FileWriter writer;

    private String logFilePath = "log/";

    public MsgFileOutput(ChatMsg chatMsg){
        this.chatMsg = chatMsg;
        this.content = chatMsg.getContent();
        this.time = chatMsg.getSendTime();
        int myId = SystemVariable.getCurrentUser().getUser_id();

        //判断是群消息还是个人消息
        if (chatMsg.isSignChat()) {
            this.id = chatMsg.getSender().getUser_id();
            logFilePath = logFilePath + "friend/";
        }
        else {
            this.id = ((Group)chatMsg.getReceiver()).getGroup_id();
            logFilePath = logFilePath + "group/";
        }


        File file = new File(logFilePath+myId);
        try {
        if (!file.exists())
            file.mkdirs();


        //判断这是自己的信息，还是对方的信息
        if ( chatMsg.getSender().getUser_id()== myId)
            id = chatMsg.getSender().getUser_id();

        files = new File(logFilePath+myId+"/"+id+".log");

        if (!files.exists())
            files.createNewFile();

        } catch (IOException e) { e.printStackTrace();}
    }
    public void input(){
        try {

            id = chatMsg.getSender().getUser_id();
            writer = new FileWriter(files,true);
            writer.append(id+"<#@&>("+time+")<#@&>"+this.content+"<%#&>\n");
            writer.flush();
            writer.close();
            System.out.println("输入成功，文件地址是："+files.getPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
